﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlServerCe;

namespace RDA
{
    public partial class Form1 : Form
    {
        public static int UserId = 0;
        public Form1()
        {
            InitializeComponent();
        }

        private void contactsBindingNavigatorSaveItem_Click(object sender, EventArgs e)
        {
            this.Validate();
            this.contactsBindingSource.EndEdit();
            this.contactsTableAdapter.Update(this.serverWebDBDataSet.Contacts);
            //this.tableAdapterManager.UpdateAll(this.serverWebDBDataSet);

        }

        private void Form1_Load(object sender, EventArgs e)
        {
           
            // TODO: This line of code loads data into the 'localPIMDataSet.Contacts' table. You can move, or remove it, as needed.
            //this.localContactsTableAdapter.Fill(this.localPIMDataSet.Contacts);
            

        }

        private void loadServerDataBotton_Click(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'serverWebDBDataSet.Contacts' table. You can move, or remove it, as needed.
            this.contactsTableAdapter.Fill(this.serverWebDBDataSet.Contacts);
        }

        private void rdaPullButton_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                verifyDatabaseExists();
                deleteTable("Contacts");
                SqlCeRemoteDataAccess rda = getRDAObject();
                rda.Pull(   "Contacts",
                            "SELECT * FROM Contacts WHERE "+UserId+"=UserId",
                            Properties.Settings.Default.ServerOleDBWebDBConnectionString,
                            RdaTrackOption.TrackingOnWithIndexes,
                            "Contacts_Errors");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }
        /// <summary>
        /// Verifies the local database file exists.  If the file doesn't exist, it will be created
        /// </summary>
        /// <returns>True if the database was created as part of the check</returns>
        private bool verifyDatabaseExists()
        {
            bool createdDatabase = false;
            using (SqlCeConnection conn = new SqlCeConnection())
            {
                conn.ConnectionString = Properties.Settings.Default.LocalPIMConnectionString;
                if (!System.IO.File.Exists(conn.Database))
                {
                    createdDatabase = true;
                    using (SqlCeEngine engine = new SqlCeEngine(Properties.Settings.Default.LocalPIMConnectionString))
                        engine.CreateDatabase();
                }
            }
            return createdDatabase;
        }

        /// Deletes a table from the local SQL Server Compact Edition database
        /// </summary>
        /// <param name="tableName">The table to delete</param>
        /// <returns>True if the table was found and deleted.  False if it wasn't found</returns>
        /// <remarks>DeleteTable will not throw if the table wasn't found</remarks>
        private bool deleteTable(string tableName)
        {
            bool tableFound = false;
            using (SqlCeConnection conn = new SqlCeConnection())
            {
                SqlCeCommand cmd = new SqlCeCommand();
                conn.ConnectionString = Properties.Settings.Default.LocalPIMConnectionString;
                cmd.Connection = conn;
                cmd.CommandText = "SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = @tableName";
                cmd.Parameters.Add("@tableName", tableName);
                conn.Open();
                if (cmd.ExecuteScalar().Equals(1))
                {
                    tableFound = true;
                    cmd.Parameters.Clear();
                    cmd.CommandText = String.Format("DROP TABLE {0}", tableName);
                    cmd.ExecuteNonQuery();
                }
            }
            return tableFound;
        }

        private SqlCeRemoteDataAccess getRDAObject()
        {
            SqlCeRemoteDataAccess rda = new SqlCeRemoteDataAccess();
            rda.InternetUrl = "http://localhost/Sync/sqlcesa30.dll";
            //rda.InternetLogin = "user";
            //rda.InternetPassword = "621844";
            rda.LocalConnectionString = Properties.Settings.Default.LocalPIMConnectionString;

            return rda;
        }

        private void loadClientDataButton_Click(object sender, EventArgs e)
        {
            this.localContactsTableAdapter.Fill(this.localPIMDataSet.Contacts);
        }

        private void saveClientDataButton_Click(object sender, EventArgs e)
        {
            this.Validate();
            this.localContactsBindingSource.EndEdit();
            this.localContactsTableAdapter.Update(this.localPIMDataSet.Contacts);
        }

        private void rdaPushButton_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                SqlCeRemoteDataAccess rda = getRDAObject();
                rda.Push("Contacts", Properties.Settings.Default.ServerOleDBWebDBConnectionString, RdaBatchOption.BatchingOn);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }

        }
        /*
        /// <summary>
        /// Client 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void loadClientDataButton_Click(object sender, EventArgs e)
        {
            this.localContactsTableAdapter.Fill(this.localPIMDataSet.Contacts);
        }

        private void saveClientDataButton_Click(object sender, EventArgs e)
        {
            this.Validate();
            this.localContactsBindingSource.EndEdit();
            this.localContactsTableAdapter.Update(this.localPIMDataSet.Contacts);
        }

        private void rdaPushButton_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                SqlCeRemoteDataAccess rda = getRDAObject();
                rda.Push("Contacts", Properties.Settings.Default.ServerOleDBWebDBConnectionString, RdaBatchOption.BatchingOn);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }
        
        */
    }
}
